import os
import sys
import re

def count(path, suffix='.js'):
  file_count = 0  #文件数量
  count_array = [0, 0, 0]   #real_code_count, comment_count, blank_count

  if os.path.isfile(path):
    print('%s is file, please check arg' % path)
    return

  #os.walk返回一个三元组.其中dirname是所有文件夹名字(不包含路径),filename是所有文件的名字(不包含路径).parent表示父目录.
  for parent, dirname, filename in os.walk(path):
    if parent.startswith(r'd:\web\caigou\su\js\jquery') or parent.startswith(r'd:\web\caigou\pm\js\jquery') or \
      parent.startswith(r'd:\web\caigou\su\calendar') or parent.startswith(r'd:\web\caigou\pm\calendar') or \
      parent.startswith(r'd:\web\caigou\common\pscws4'):
      continue
    for fn in filename:
      shortname, extension = os.path.splitext(fn)
      if extension == suffix:
        file_count += 1
        count_array = list(x+y for x, y in zip(count_array, count_file(os.path.join(parent, fn))))
    # print(parent)

  print('file_count: %d' % file_count)
  print(count_array)

def count_file(filename):
  if filename.startswith(r'd:\web\caigou\su\js\jquery') or \
    filename.startswith(r'd:\web\caigou\su\calendar') or \
    filename.startswith(r'd:\web\caigou\pm\js\jquery') or \
    filename.startswith(r'd:\web\caigou\pm\calendar'):
    return [0,0,0]
  print(filename)
  all_count = 0
  real_code_count = 0
  comment_count = 0
  blank_count = 0

  comment_pattern = re.compile('^(\s)*//')

  with open(filename, 'r', encoding='utf-8') as f:
    for line in f:
      all_count += 1
      if comment_pattern.match(line):
        comment_count += 1
      if line.strip() == '':
        blank_count += 1

  real_code_count = all_count - comment_count - blank_count
  return [real_code_count, comment_count, blank_count]

if __name__ == '__main__':
  count(r'd:\web\caigou\pm')
  count(r'd:\web\caigou\su')
